#include "stdafx.h"
#include "DynamicLengthPool.h"

bool CDynamicLengthPool::AddBit(bool bBitValue)
{
	if (m_bResetForRead)
	{
		return false;
	}

	if (m_nCurBits == 0 || m_rVecBytes.empty())
	{
		m_nCurBits = 0;
		m_rVecBytes.push_back(0);
	}

	if (bBitValue)
	{
		m_rVecBytes.back() |= 1 << m_nCurBits;
	}

	if (++m_nCurBits == 8)
	{
		m_nCurBits = 0;
	}

	m_curPos = m_rVecBytes.size();

	return true;
}

bool CDynamicLengthPool::GetBit() const
{
	if( m_nCurBits != 0 )
	{
		m_curPos--;
	}

	if (m_curPos >= m_rVecBytes.size())
	{
		return false;
	}

	bool bRet = (m_rVecBytes[m_curPos] & (1 << m_nCurBits)) != 0;
	if (++m_nCurBits == 8)
	{
		m_nCurBits = 0;
	}

	++m_curPos;
	return bRet;
}

bool CDynamicLengthPool::Read(char* cpChars, size_t nSize) const
{
	if (m_nCurBits)
	{
		m_nCurBits = 0;
	}
	if (m_rVecBytes.size() - m_curPos >= (size_t)nSize)
	{
		if( nSize > 0 )
		{
			memcpy_s(cpChars, nSize, (const char *)&m_rVecBytes[m_curPos], nSize);
		}
		m_curPos += nSize;
		return true;
	}
	return false;
}

bool CDynamicLengthPool::Write(const char* cpChars, size_t nSize)
{
	if (m_bResetForRead)
	{
		return false;
	}
	m_nCurBits = 0;
	m_rVecBytes.insert(m_rVecBytes.end(), cpChars, cpChars + nSize);

	m_curPos = m_rVecBytes.size();
	return true;
}

unsigned int CDynamicLengthPool::GetCurPosition()
{
	return  m_curPos;
}

void CDynamicLengthPool::SetCurPosition( unsigned int nCurPos)
{
	if( nCurPos <= m_rVecBytes.size() )
	{
		m_curPos = nCurPos;
	}
}

void CDynamicLengthPool::_ModifySizeT( unsigned int nPosition, unsigned int nValue)
{
	if( nPosition + sizeof( unsigned int) > m_rVecBytes.size() )
	{
		return;
	}

	char* pValue = (char*)(&nValue);

	for( unsigned int i = 0; i < sizeof( unsigned int); i++ )
	{
		m_rVecBytes[nPosition + i] = *pValue;
		pValue++;
	}
}
